﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Simple.Common
{
    public static class SimpleJsonHelper
    {
        /// <summary>
        /// 解析字符串为对象
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="input">输入参数</param>
        /// <returns></returns>
        public static T Deserialize<T>(string input) where T : class
        {
            if (string.IsNullOrEmpty(input)) return null;
            return JsonConvert.DeserializeObject<T>(input);
        }

        /// <summary>
        /// 编码对象成JSON
        /// </summary>
        /// <param name="input">输入对象</param>
        /// <returns></returns>
        public static string Serialize(this object instance)
        {
            //return JsonConvert.SerializeObject(instance);

            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            //这里使用自定义日期格式，如果不使用的话，默认是ISO8601格式  
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
            return JsonConvert.SerializeObject(instance, Formatting.None, timeConverter);

            //return JsonConvert.SerializeObject(instance, new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
        }

    }
}
